package cn.com.xjnt.vas.ordering.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.frameworks.core.repository.BaseRepository;
import com.frameworks.core.service.AbstractBaseService;
import com.frameworks.utils.PathUtils;

import cn.com.xjnt.vas.ordering.domain.entity.FoodMenu;
import cn.com.xjnt.vas.ordering.domain.entity.Hospital;
import cn.com.xjnt.vas.ordering.repository.FoodMenuRepository;
import cn.com.xjnt.vas.ordering.service.FoodMenuService;

/**
 * 类说明：
 * 
 * @author 作者 LUXIN
 * @version 创建时间：2016年5月13日16:33:44
 */
@Service
@Transactional
public class FoodMenuServiceImpl extends AbstractBaseService<FoodMenu, Long> implements FoodMenuService {
    private static final Logger logger = LogManager.getLogger(FoodMenuServiceImpl.class);
    
    // 初始化附件地址
    private static String bgImgUrl = PathUtils.getWebRootPath() + File.separator + "static" + File.separator
            + "ordering" + File.separator + "bgImg" + File.separator;
    private static String focusImgUrl = PathUtils.getWebRootPath() + File.separator + "static" + File.separator
            + "ordering" + File.separator + "focusImg" + File.separator;
    private static String cornerImgUrl = PathUtils.getWebRootPath() + File.separator + "static" + File.separator
            + "ordering" + File.separator + "cornerImg" + File.separator;
    
    @Autowired
    private FoodMenuRepository foodMenuRepository;
    @Override
    protected BaseRepository<FoodMenu, Long> getBaseRepository() {
        return foodMenuRepository;
    }

    @Override
    public void save(FoodMenu entity) {
        super.saveOrUpdate(entity);
    }

    @Override
    public void update(FoodMenu entity) {
        super.saveOrUpdate(entity);
    }

    @Override
    public void saveFoodMenu(FoodMenu model, MultipartFile[] bgImg, MultipartFile[] focusImg,
            MultipartFile[] cornerImg) {
        try {
            if (bgImg.length != 0) {
                if (bgImg[0].getSize() != 0l) {
                    String name = new Date().getTime()+"_"+ bgImg[0].getOriginalFilename();
                    String path = saveFileFromInputStream(bgImg[0].getInputStream(), bgImgUrl, name);
                    String url = pathToUrl(path);
                    model.setBgName(name);
                    model.setBgImg(path);
                    model.setBgUrl(url);
                }
            }
            if (focusImg.length != 0) {
                if (focusImg[0].getSize() != 0l) {
                    String name = new Date().getTime()+"_"+ focusImg[0].getOriginalFilename();
                    String path = saveFileFromInputStream(focusImg[0].getInputStream(), focusImgUrl, name);
                    String url = pathToUrl(path);
                    model.setFocusName(name);
                    model.setFocusImg(path);
                    model.setFocusUrl(url);
                }
            }
            if (cornerImg.length != 0) {
                if (cornerImg[0].getSize() != 0l) {
                    String name = new Date().getTime()+"_"+ cornerImg[0].getOriginalFilename();
                    String path = saveFileFromInputStream(cornerImg[0].getInputStream(), cornerImgUrl, name);
                    String url = pathToUrl(path);
                    model.setCornerName(name);
                    model.setCornerImg(path);
                    model.setCornerUrl(url);
                }
            }
            this.save(model);
        } catch (IOException e) {
            logger.error("菜单附件保存至服务器失败：", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void updateFoodMenu(FoodMenu model, MultipartFile[] bgImg, MultipartFile[] focusImg,
            MultipartFile[] cornerImg) {
        try {
            if (bgImg.length != 0) {
                if (bgImg[0].getSize() != 0l) {
                    String name = new Date().getTime()+"_"+ bgImg[0].getOriginalFilename();
                    String path = saveFileFromInputStream(bgImg[0].getInputStream(), bgImgUrl, name);
                    String url = pathToUrl(path);
                    model.setBgName(name);
                    model.setBgImg(path);
                    model.setBgUrl(url);
                }
            }
            if (focusImg.length != 0) {
                if (focusImg[0].getSize() != 0l) {
                    String name = new Date().getTime()+"_"+ focusImg[0].getOriginalFilename();
                    String path = saveFileFromInputStream(focusImg[0].getInputStream(), focusImgUrl, name);
                    String url = pathToUrl(path);
                    model.setFocusName(name);
                    model.setFocusImg(path);
                    model.setFocusUrl(url);
                }
            }
            if (cornerImg.length != 0) {
                if (cornerImg[0].getSize() != 0l) {
                    String name = new Date().getTime()+"_"+ cornerImg[0].getOriginalFilename();
                    String path = saveFileFromInputStream(cornerImg[0].getInputStream(), cornerImgUrl, name);
                    String url = pathToUrl(path);
                    model.setCornerName(name);
                    model.setCornerImg(path);
                    model.setCornerUrl(url);
                }
            }
            this.update(model);
        } catch (IOException e) {
            logger.error("菜单附件保存至服务器失败：", e.getMessage());
            e.printStackTrace();
        }
    }
    

    @Override
    public void deleteImg(String path) {
        try {
            deleteFileInServer(path);
        } catch (IOException e) {
            logger.error("从服务器删除附件失败：", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public List<FoodMenu> findByTypeAndHospital(int type,Hospital hospital){
        return foodMenuRepository.findByTypeAndHospital(type, hospital);
    }
    
    /**
     * 保存文件
     * 
     * @param stream
     * @param path
     * @param filename
     * @throws IOException
     */
    public String saveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
        File FileDir = new File(path);
        // 文件路径不存在
        if (!FileDir.isDirectory()) {
            FileDir.mkdirs();
        }

        String dir = path + filename;
        FileOutputStream fs = new FileOutputStream(dir);
        byte[] buffer = new byte[1024 * 1024];
        int byteread = 0;
        @SuppressWarnings("unused")
        int bytesum = 0;
        while ((byteread = stream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
        return dir;
    }

    /**
     * 删除已上传的附件，根据文件真实路径删除
     * 
     * @param url
     * @throws IOException
     */
    public void deleteFileInServer(String url) throws IOException {
        File file = new File(url);
        if (file.exists()) {
            file.delete();
        }
    }
    /**
     * 将真实物理地址转化为web访问地址
     * @param path
     * @return
     */
    public String pathToUrl(String path){
        String url = path.replace("\\","/");
        String temp[] = url.split("vas");
        return temp[1];
    }
}
